package com.app.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * @author 540126629
 * @version 创建时间：2015-1-5 下午3:48:47
 * 
 */


// 操作数据库工具
public class Utils_DB {
	
	
	private static String TAG = Utils_DB.class.getSimpleName();
	
	//private DatabaseHelper Database ;
	
	/*
	public static Utils_DB createDB(String DBName){
		Utils_DB db = new Utils_DB();
		//db.createDB(DBName);
		// 创建数据库
		createDB(DBName)
		
		return db;
	}
	
	private Utils_DB(){
		
	}
	
	private void createDB(String DBName){
		
	}
	*/
	
	/*
	public void addItem(Object obj){
		
	}
	
	public void deleteItem(){
		
	}
	*/
	
	/**
	 * 重命名某张表
	 * 
	 * @param OldName
	 *            旧的表名； NewName 新的表名
	 * @return 注意：表名不区分大小写
	 */
	public static void TableRename(Context context, String OldName, String NewName) {
		SQLiteOpenHelper mOpenHelper = DatabaseHelper
				.getInstance(context);
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		
		try{
		db.execSQL("alter table " + OldName.trim() + " rename to "
				+ (NewName.trim()) + ";");
		}catch(SQLException e){
			
			e.printStackTrace();
			
		}
		
		
	}
	
	/**
	 * http://www.cnblogs.com/xytop/articles/1277125.html
	 * @author matengfei
	 * @param context
	 * @param table_name
	 */
	public static void TableQuery(Context context, String table_name){
		
		StringBuffer count = new StringBuffer("");
		SQLiteOpenHelper mOpenHelper = DatabaseHelper
				.getInstance(context);
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor cursor = null;
		try {
			
			String  sql = "select * from "+ table_name;
			//System.out.println("Quer_Table: "+table_name);
			Utils_Log.d(TAG, "TableQuery: "+table_name);
			cursor = db.rawQuery(sql, null);
			if(cursor.moveToFirst() == false) return;	
//			while (!cursor.isLast()) {
//				count.append(cursor.getString(0));  
//				count.append(",");
//				cursor.moveToNext();
//			}
//			count.append(cursor.getString(0));
			
			String ColumnName = "";
			int j = 0;
			j = cursor.getColumnCount();
            for(int k = 0; k<j; k++) // 打印列名
            {
            	  String v = cursor.getColumnName(k);
        		  v = String.format("%12s", v);
        		  ColumnName += v;
                //System.out.print(cursor.getColumnName(k));    // cursor.getColumnLabel(k+1)
                //System.out.print("   ");
           }
            Utils_Log.d(TAG, ColumnName);  
           //System.out.println();
           
//          while(cursor!=null) // 逐行打印   结尾处cursor会变成null
//           {
//                for(int i=0;i<j;i++)
//                {
//                    System.out.print(cursor.getString(i));  // rs.getString(i+1)
//                    System.out.print("  ");
//               }
//                cursor.moveToNext(); 
//               System.out.println();
//          }
 
// 如果不试的话, 也会怀疑cursor为-1          
          do{
        	  String result = "";
        	  for(int i=0;i<j;i++)
              {
        		  String v = cursor.getString(i);
        		  v = String.format("%12s", v);
        		  result += v;
                  //System.out.print(cursor.getString(i));  // rs.getString(i+1)
                  //System.out.print("  ");
             }
        	 // System.out.println();
        	  Utils_Log.d(TAG, result);	
          }while(cursor.moveToNext());
          
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			if(cursor != null) cursor.close();
		}
	}

	
	/**
	 * 判断某张表是否存在
	 * 
	 * @param tabName
	 *            表名
	 * @return
	 */
	public static boolean TableIsExist(Context context, String tableName) {
		boolean result = false;
		if (tableName == null) {
			return false;
		}
		SQLiteOpenHelper mOpenHelper = DatabaseHelper
				.getInstance(context);
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor cursor = null;
		try {
			String sql = "select count(*) as c from Sqlite_master  where type ='table' and name ='"
			+ tableName.trim() + "' ";
			cursor = db.rawQuery(sql, null);
			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);
				if (count > 0) {
					result = true;
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			cursor.close();
		}
		cursor.close();
		return result;
	}
	
	/**
	 * 获取数据库中的表的个数
	 * 
	 * @param
	 * @return int 表的个数
	 */
	public static int TableCount(Context context) {
		int count = 0;
		SQLiteOpenHelper mOpenHelper = DatabaseHelper
				.getInstance(context);
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor cursor = null;
		try {
			String sql = "select count(*) as c from Sqlite_master where type ='table'";
			cursor = db.rawQuery(sql, null);
			if (cursor.moveToNext()) {
				count = cursor.getInt(0);
			}

		} catch (Exception e) {
			// TODO: handle exception
			cursor.close();
		}
		cursor.close();
		return count;
	}
	
	
	// 获取数据库中的所有表名
	public static String TableName_ALL(Context context) {
		StringBuffer count = new StringBuffer("");
		SQLiteOpenHelper mOpenHelper = DatabaseHelper
				.getInstance(context);
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor cursor = null;
		try {
			String sql = "select name from Sqlite_master where type ='table'";
			cursor = db.rawQuery(sql, null);
			cursor.moveToFirst();
			while (!cursor.isLast()) {
				count.append(cursor.getString(0));
				count.append(",");
				cursor.moveToNext();
			}
			count.append(cursor.getString(0));
		} catch (Exception e) {
			// TODO: handle exception
			cursor.close();
		}
		cursor.close();
		return count.toString();
	}
	
	/**
	 * 删除某张表
	 * 
	 * @param tableName
	 *            表名
	 * @return
	 */
	public static void DeletTable(Context context, String tableName) {
		SQLiteOpenHelper mOpenHelper = DatabaseHelper.getInstance(context);
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		db.execSQL("drop table " + tableName.trim() + ";");
		db.close();
	}

	
	/** 清空表
	 * 
	 */
	public static void ClearTable(Context context, String tableName) {
		SQLiteOpenHelper mOpenHelper = DatabaseHelper.getInstance(context);
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		db.execSQL("delete from " + tableName.trim() + ";");
		db.close();
		
	}
	
	/**
	 * 执行sql语句
	 * @author matengfei
	 * @param context
	 * @param sql
	 */
	public static void execSQL(Context context, String sql){ 
		SQLiteOpenHelper mOpenHelper = DatabaseHelper.getInstance(context);
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		db.execSQL(sql);	
		db.close();
	}
	
	
	/**
	 * 插入内容
	 * @author matengfei
	 * @param context
	 * @param TableName
	 * @param values
	 */
	public static boolean Insert(Context context, String TableName, ContentValues values){
		SQLiteOpenHelper mOpenHelper = DatabaseHelper.getInstance(context);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase(); // 取得数据库操作实例
		long result = db.insert( TableName , null, values);
		 db.close();
		 
		 if(result <= 0){
			 return false;
		 }
		 
		 return true;
		 
	}
	
}




